package org.admin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    private StringRedisTemplate redis;
    public void setItem(String key, String value){
        redis.opsForValue().set(key, value);
    }
    public void setItem(String key, String value, Date expire){
        this.setItem(key, value);
        if(expire!= null) {
            redis.expire(key, expire.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }
    }

    public String getItem(String key){
        ValueOperations<String, String> ops = redis.opsForValue();
        return ops.get(key);
    }

    public int count(String pattern){
        Set<String> keys = redis.keys(pattern);
        if (keys == null) return 0;
        return keys.size();
    }
    public void remove(String key) {
        redis.delete(key);
    }
}
